package com.example.projectmgmt.controller;

import com.example.projectmgmt.dto.ProjectDTO;
import com.example.projectmgmt.dto.ProjectDetailDTO;
import com.example.projectmgmt.service.ProjectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/api/projects")
public class ProjectController{

    private final ProjectService projectService;

    @Autowired
    public ProjectController(ProjectService projectService) {
        this.projectService = projectService;
    }

    @GetMapping
    public ResponseEntity<List<ProjectDTO>> getAllProjects(
            @RequestParam(required = false) String search) {
        List<ProjectDTO> projects = projectService.findAllProjects(search);
        return ResponseEntity.ok(projects);
    }

    @PostMapping
    public ResponseEntity<ProjectDTO> createProject(@Valid @RequestBody ProjectDTO projectDTO) {
        ProjectDTO createdProject = projectService.createProject(projectDTO);
        return new ResponseEntity<>(createdProject, HttpStatus.CREATED);
    }

    @GetMapping("/{projectNo}")
    public ResponseEntity<ProjectDetailDTO> getProject(@PathVariable String projectNo) {
        ProjectDetailDTO project = projectService.findProjectByNo(projectNo);
        return ResponseEntity.ok(project);
    }

    @PutMapping("/{projectNo}")
    public ResponseEntity<ProjectDTO> updateProject(
            @PathVariable String projectNo,
            @Valid @RequestBody ProjectDTO projectDTO) {
        ProjectDTO updatedProject = projectService.updateProject(projectNo, projectDTO);
        return ResponseEntity.ok(updatedProject);
    }

    @DeleteMapping("/{projectNo}")
    public ResponseEntity<Void> deleteProject(@PathVariable String projectNo) {
        projectService.deleteProject(projectNo);
        return ResponseEntity.noContent().build();
    }
}